<!-- 组织架构图左侧组件 -->

<template>
  <a-layout class="layout-demo">
    <a-layout-sider
      class="layout-sider"
      collapsible
      breakpoint="xl"
      reverse-arrow
      style="box-shadow: none; padding: 0"
      @collapse="collapse"
    >
      <div class="role-list" v-show="!isCollapsed">
        <div>
          <a-scrollbar style="height: 600px; overflow: auto">
            <div class="scroll">
              <a-input-search
                allow-clear
                class="search"
                placeholder="输入分类名称"
                v-model="searchVal"
              />

              <div class="scroll-content">
                <a-tree
                  v-model:selected-keys="selectedKeys"
                  showLine
                  @select="select"
                  :fieldNames="{
                    key: 'id',
                    title: 'department',
                    children: 'children'
                  }"
                  blockNode
                  :data="treeData"
                  v-model:expanded-keys="expandKey"
                >
                  <template #switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #title="nodeData">
                    <template
                      v-if="
                        ((index = getMatchIndex(nodeData.department)),
                        index < 0)
                      "
                    >
                      <span
                        :style="{
                          paddingLeft:
                            nodeData.level > 2
                              ? '32px'
                              : (nodeData.level - 1) * 16 + 'px'
                        }"
                      >
                        {{ nodeData?.department }}
                      </span></template
                    >
                    <span v-else>
                      {{ nodeData?.department?.substr(0, index) }}
                      <span style="color: var(--color-primary-light-4)">
                        {{
                          nodeData?.department?.substr(index, searchVal.length)
                        }} </span
                      >{{
                        nodeData?.department?.substr(index + searchVal.length)
                      }}
                    </span>
                  </template>
                </a-tree>
              </div>
            </div>
          </a-scrollbar>
        </div>
      </div>
      <template #trigger="{ collapsed }">
        <IconCaretRight v-if="collapsed"></IconCaretRight>
        <IconCaretLeft v-else></IconCaretLeft>
      </template>
    </a-layout-sider>
  </a-layout>
</template>

<script lang="ts" setup>
import clonedeep from 'lodash.clonedeep';
import { flatTreeWithChildren } from '@/utils/utils';
import type { treeDataType } from '../../type';
const emit = defineEmits(['clickTree']);
const props = withDefaults(
  defineProps<{
    data: treeDataType; // 是否显示对话框
    id: number; // 组织id
  }>(),
  {
    data: () => ({}),
    id: 0
  }
);
let searchVal = ref(''); // 搜索框
let selectedKeys = ref([]); // 选中的key
let originTreeData = ref<treeDataType[]>([]); // 储存最初的树形数据
let expandKey: any = ref([]); // 储存当前搜索要展开的选项

// 搜索值
const searchData = (keyword: string) => {
  const loop = (data: any) => {
    const result: any = [];
    data.forEach((item: any) => {
      if (item.department.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
          expandKey.value.push(item.id);
        }
      }
    });
    return result;
  };
  return loop(originTreeData.value);
};
let isCollapsed = ref(false); // 判断是否收起
const collapse = (collapsed: boolean) => {
  isCollapsed.value = collapsed;
};
/* 储存实时的属性数据 */
const treeData = computed(() => {
  if (!searchVal.value) return originTreeData.value;
  return searchData(searchVal.value);
});

watch(
  () => props.id,
  (newVal: number) => {
    if (newVal > 0) {
      const temp = flatTreeWithChildren([props.data]).find(
        (item: any) => item.id === props.id
      );
      searchData(temp.department);
      selectedKeys.value = [newVal];
      emit('clickTree', temp);
    }
  }
);
watch(
  () => props.data,
  (val) => {
    originTreeData.value = [val];

    // 如果是从组织机构列表跳转过来则直接显示对应id的数据
    if (props.id > 0) {
      const temp = flatTreeWithChildren([val]).find(
        (item: any) => item.id === props.id
      );
      // 直接用跳转过来组织的名字来搜索展开子树，然后将id赋值给selectedKeys
      searchData(temp.department);
      selectedKeys.value = [props.id];
      emit('clickTree', temp);
    } else selectedKeys.value = [originTreeData.value[0].id]; // 默认选中第一条数据
  }
);

// 获取符合的数据
const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

// 点击树触发
const select = (e: any, { selectedNodes }: any) => {
  emit('clickTree', selectedNodes[0]);
};
</script>

<style scoped lang="less">
.layout-demo {
  // width: 350px;
}
.layout-sider {
  width: 350px;
}
:deep(.arco-layout-sider-trigger) {
  position: absolute;
  bottom: 0px;
  right: 20px;
  width: 20px !important;
  background: transparent;
}
.arco-layout {
  flex: none !important;
}
.role-list {
  flex: 1;
  padding: 10px;
  box-shadow: -10px 0 3px rgba(0, 0, 0, 0.5);
  // border: 1px solid #ccc;
  // width: 100%;
  // height: 100%;
  background-color: #fff;
  // border: 1px solid #ccc;
  // background-color: #f5f7fa;

  // height: 300px;
  .scroll {
    padding: 10px;
    .search {
      background-color: #fff;
      height: 40px;
      border: 1px solid #ccc;
    }
  }
}
:deep(.arco-tree-node-indent) {
  width: 0px;
  height: 0px;
}
</style>
